import 'dart:convert';

import 'package:get/get.dart';
import 'package:kkhousekeep/config/constant.dart';
import 'package:kkhousekeep/models/home_room_entity.dart';
import 'package:kkhousekeep/net/me_connect.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:kkhousekeep/page/home/home_page_controller.dart';
import 'package:kkhousekeep/page/me/me_controller.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';
import 'package:kkhousekeep/tools/toast_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../tools/shared_preferences.dart';
import 'house_notification_page.dart';

class MyHouseController extends GetxController {
  var hasNewMsg = false.obs;

  var currentRoom = HomeRoomObjList()
      .copyWith(
        roomId: -1,
        cityName: '',
        communityName: '',
        buildingName: '',
        unitName: '',
        roomName: '',
      )
      .obs;

  var rooms = <HomeRoomObjList>[].obs;

  late MeConnect _meConnect;

  @override
  void onInit() {
    _meConnect = Get.isRegistered<MeConnect>()
        ? Get.find<MeConnect>()
        : Get.put(MeConnect());
    super.onInit();
    _loadNetworkData();
  }

  Future<void> _loadNetworkData() async {
    currentRoom.value = await _meConnect.getRoomInfo();
    rooms.value = await _meConnect.getRooms();
    if (currentRoom.value.roomId != -1) {
      rooms
          .removeWhere((element) => element.roomId == currentRoom.value.roomId);
    }
    if (Get.arguments != null && Get.arguments == ArgumentKey.hasNewMsg) {
      hasNewMsg.value = true;
    }
  }

  Future<void> switchHouse(HomeRoomObjList room) async {
    var response = await _meConnect.switchHouse(roomId: room.roomId);
    if(response == null){
      return;
    }
    if (response.code == ResponseCode.success) {
      ToastUtils.showToast(tip: "切换成功");
      await getSp().setAccessToken(response.obj.token);
      await saveRoomInfo(room);
      await _loadNetworkData();
    } else {
      DialogUtil.showNetworkFail();
    }
  }

  Future saveRoomInfo(HomeRoomObjList info) async {
    String key = SpKey.roomInfo;
    HomeController homeController = Get.isRegistered()
        ? Get.find<HomeController>()
        : Get.put(HomeController());
    MeController meController = Get.isRegistered<MeController>()
        ? Get.find<MeController>()
        : Get.put(MeController());
    meController.description.value =
        '${info.cityName}${info.communityName}${info.buildingName}'
        '${info.unitName}${info.roomName}';
    homeController.address.value = '${info.communityName}${info.buildingName}'
        '${info.unitName}${info.roomName}';
    homeController.roomInfo = info;

    var sp = await SharedPreferences.getInstance();
    sp.setString(key, jsonEncode(info.toJson()));
  }

  void buildAppBarNotificationBtn() {
    Get.to(() => const HouseNotificationPage())?.whenComplete(() {
      hasNewMsg.value = false;
    });
  }
}
